package lk.icta.common.dao.impl;


import lk.icta.user.common.UserRuntimeException;
import org.hibernate.Session;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Duminda Dharmakeerthi
 */
@Repository
public class BaseDAO {
    protected static final String SPACER = " : ";
    protected final Logger logger;
    protected EntityManager em;
    protected Connection connection;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    protected BaseDAO() {
        logger = LoggerFactory.getLogger(this.getClass());
    }

    protected void handleException(String msg, int code) {
        logger.error(msg);
        throw new UserRuntimeException(msg, code);
    }

    protected void handleException(String msg, int code, Exception e) {
        logger.error(msg, e);
        throw new UserRuntimeException(msg, code, e);
    }

    protected Connection getConnection() throws SQLException {
        Session session = (Session) em.getDelegate();
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
        ConnectionProvider cp = sfi.getConnectionProvider();
        return cp.getConnection();
    }

    protected void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
